package com.xuebank.nfe.nfecar.activity


import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.support.annotation.RequiresApi
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.*
import android.widget.LinearLayout
import com.wzn.libaray.utils.Logger
import com.wzn.libaray.utils.cache.SharedPreferencesUtil
import com.xuebank.nfe.nfecar.MainActivity

import com.xuebank.nfe.nfecar.R
import com.xuebank.nfe.nfecar.beas.BaseActivity
import com.xuebank.nfe.nfecar.utils.XueBankUtils
import com.xuebank.nfe.nfecar.utils.bridge.BridgeHandler
import com.xuebank.nfe.nfecar.utils.bridge.BridgeWebView
import com.xuebank.nfe.nfecar.utils.bridge.BridgeWebViewClient
import com.xuebank.nfe.nfecar.utils.bridge.CallBackFunction
import com.xuebank.nfe.nfecar.utils.statusbar.StatusBarUtil
import org.json.JSONObject
import java.util.HashMap

@RequiresApi(Build.VERSION_CODES.M)
class SecondActivity : BaseActivity(){
    private var second_ll:LinearLayout? = null
    private var mWebView: BridgeWebView? = null
    private var webSettings: WebSettings? = null
    private val APP_CACAHE_DIRNAME = "/webcache"
    private var newWebView: BridgeWebView? = null
    private var actionUrl: String? = null
    private var refererUrl = ""
    private var mUploadCallbackAboveL: ValueCallback<Array<Uri?>>? = null
    private val FILECHOOSER_RESULTCODE = 101
    private var mUploadMessage: ValueCallback<Uri>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
        val intent = intent
        actionUrl = intent.getStringExtra("url")
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.white))
        webViewSendRequest("")
        initWebView()
    }

    override fun findViews() {
        super.findViews()
        second_ll= findViewById(R.id.activity_second_webview)
        mWebView = findViewById(R.id.activity_second_bridgeWebView)

    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        webSettings = mWebView?.settings
        webSettings?.javaScriptEnabled = true
        val userAgentString = webSettings?.userAgentString
        webSettings?.allowFileAccess = true
        webSettings?.setSupportZoom(false)
        webSettings?.allowContentAccess = true
        webSettings?.useWideViewPort = true
        webSettings?.loadWithOverviewMode = true
        webSettings?.loadsImagesAutomatically = true
        val defaultUserAgent = webSettings?.getUserAgentString()
        if (Build.VERSION.SDK_INT >= 11)
            mWebView?.settings?.allowContentAccess = true
        if (Build.VERSION.SDK_INT >= 21)
            mWebView?.settings?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        if (webSettings != null) {
            setWebViewCacheMode(webSettings!!)

        }
    }

    private fun webViewSendRequest(params: String) {
//        synCookies(this,actionUrl?:"")
        var params = params
        params = params.replace("[\\r\\n\\t]+".toRegex(), "")
        //        ICBCLogUtil.log("actionUrl", actionUrl + params);
        if ("" == params) {
            if (TextUtils.isEmpty(refererUrl)) {
                refererUrl = actionUrl?:""
                mWebView?.loadUrl(actionUrl)
            } else {
                val extraHeaders = HashMap<String, String>()
                extraHeaders.put("Referer", refererUrl)
                mWebView?.loadUrl(actionUrl, extraHeaders)
            }
            //        } else {
            //            mWebView.postUrl(actionUrl, EncodingUtils.getBytes(params, "BASE64"));
        }
    }

    fun setWebViewCacheMode(webViewCacheMode: WebSettings) {
        webSettings?.setRenderPriority(WebSettings.RenderPriority.HIGH)
        webSettings?.javaScriptCanOpenWindowsAutomatically = true
        // 支持多窗口
        webSettings?.setSupportMultipleWindows(true)
        // 开启 DOM storage API 功能
        webSettings?.domStorageEnabled = true
        // 开启 Application Caches 功能
        webSettings?.setAppCacheEnabled(true)
        val cacheDirPath = getContext().filesDir.absolutePath + APP_CACAHE_DIRNAME
        //设置数据库缓存路径
        webSettings?.setDatabasePath(cacheDirPath)
        //设置  Application Caches 缓存目录
        webSettings?.setAppCachePath(cacheDirPath)
        webSettings?.setDatabaseEnabled(true)
        //通过xml资源文件获得animation实例
        //        iv_background.setImageResource(R.drawable.anim_xb);
        //        xbAnimation = (AnimationDrawable) iv_background.getDrawable();
        mWebView?.webChromeClient = object : WebChromeClient() {

            override fun onCreateWindow(view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message): Boolean {
                newWebView = BridgeWebView(getContext())
                newWebView?.webViewClient = object : WebViewClient() {
                    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                        val intent = Intent(getContext(), SecondActivity::class.java)
                        intent.putExtra("url", url)
                        startActivity(intent)
                        return true
                    }
                }
                //                initWebView(newWebView);//初始化webview
                second_ll?.addView(newWebView)
                val transport = resultMsg.obj as WebView.WebViewTransport//以下的操作应该就是让新的webview去加载对应的url等操作。
                transport.webView = newWebView
                resultMsg.sendToTarget()
                return true
            }

            override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                result?.confirm()
                return true
            }

            override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri?>>?, fileChooserParams: FileChooserParams?): Boolean {
                mUploadCallbackAboveL = filePathCallback;
    val i =  Intent(Intent.ACTION_GET_CONTENT);
    i.addCategory(Intent.CATEGORY_OPENABLE);
    i.setType("image/*");
    startActivityForResult(
            Intent.createChooser(i, "File Browser"),
            FILECHOOSER_RESULTCODE);

                return true

            }

            override fun onExceededDatabaseQuota(url: String?, databaseIdentifier: String?, quota: Long, estimatedDatabaseSize: Long, totalQuota: Long, quotaUpdater: WebStorage.QuotaUpdater?) {
                //设置数据库存储大小
                quotaUpdater?.updateQuota(estimatedDatabaseSize * 2)
            }
            /*** 视频播放相关的方法  */

        }
        mWebView?.webViewClient = object : BridgeWebViewClient(mWebView) {


            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                Log.i(TAG, url)
                //                start();
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                requestData()
                //                stop();
                //                homeHeadView.setVisibility(View.GONE);
                mWebView?.setOnLongClickListener(View.OnLongClickListener { true })

                mWebView?.setOnLongClickListener(View.OnLongClickListener { true })
                val cookieManager = CookieManager.getInstance()
                val CookieStr = cookieManager.getCookie(url)
                if (CookieStr != null) {
                    SharedPreferencesUtil.getInstance(this@SecondActivity).applyString(MainActivity.COOKIE,CookieStr)
                    Logger.d("登录页的cookie", CookieStr)
//                    }
                }


            }


            override  fun onLoadResource(view: WebView?, url: String?) {
                Log.i(TAG, url)
                super.onLoadResource(view, url)
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                Log.e(TAG, url)
                return super.shouldOverrideUrlLoading(view, url)
            }

            override  fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                super.onReceivedError(view, request, error)
            }
        }

    }


    private fun requestData() {
        mWebView?.registerHandler("XueBankWebViewJavascriptBridge") { data, function ->
            Log.e("BridgeHandler", data)
            var jsonObject: JSONObject? = null
            try {
                val xbutils = XueBankUtils(this@SecondActivity)
                jsonObject = JSONObject(data)
                val send_action = jsonObject.getString("action")
                xbutils.doBridgeHandler(data) { result ->
                    Log.e("onCallBack", result)
                    function.onCallBack(result)
                }

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

   override fun onDestroy() {
        if (null != mWebView) {
            mWebView?.removeAllViews()
            mWebView?.destroy()
        }
        super.onDestroy()
    }

   override fun onBackPressed() {
        this@SecondActivity.finish()
        super.onBackPressed()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
         if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
             var  result :Uri ?=null
             if (data == null || resultCode != RESULT_OK) {
                 result = null
             } else {
                 result = data.data
             }
        if (mUploadCallbackAboveL != null) {
            onActivityResultAboveL(requestCode, resultCode, data);
        } else if (mUploadMessage != null) {
            mUploadMessage?.onReceiveValue(result);
            mUploadMessage = null;
        }
    }
    }


    private fun onActivityResultAboveL(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode != FILECHOOSER_RESULTCODE || mUploadCallbackAboveL == null) {
            return
        }
        var results: Array<Uri?>? = null
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
            } else {
                val dataString = data.dataString
                val clipData = data.clipData
                if (clipData != null) {
                    results = arrayOfNulls(clipData.itemCount)
                    for (i in 0 until clipData.itemCount) {
                        val item = clipData.getItemAt(i)
                        results[i] = item.uri
                        Log.e(TAG, "onActivityResultAboveL: " + results[i]?.path)
                    }
                }
                if (dataString != null)
                    results = arrayOf(Uri.parse(dataString))
                Log.e(TAG, "onActivityResultAboveL: " + results?.size)
            }
        }
        mUploadCallbackAboveL?.onReceiveValue(results)
        mUploadCallbackAboveL = null
        return
    }


       /**
     * 同步一下cookie
     */
    fun  synCookies(context: Context, url:String ) {
        CookieSyncManager.createInstance(context);
        val cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
//        cookieManager.removeSessionCookie();//移除
        cookieManager.setCookie(url, SharedPreferencesUtil.getInstance(this).getString(MainActivity.COOKIE));
        CookieSyncManager.getInstance().sync();
    }

}
